// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.TmpJmGoodsOrder;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.TmpJmGoodsOrderMapper;
import com.fowo.api.model.tmp.jm.goods.order.TmpJmGoodsOrderExcelPo;
import com.fowo.api.model.tmp.jm.goods.order.TmpJmGoodsOrderImportPo;
import com.fowo.api.model.tmp.jm.goods.order.TmpJmGoodsOrderItemVo;
import com.fowo.api.model.tmp.jm.goods.order.TmpJmGoodsOrderSearchParamPo;
import com.fowo.api.model.tmp.jm.goods.order.TmpJmGoodsOrderVo;
import com.fowo.api.service.TmpJmGoodsOrderService;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 独立站订单临时表 服务实现类
 * @author 蜂窝蜜造平台 配置人：鹿丙涛
 */
@Service
@Slf4j
@DataObjectType(TmpJmGoodsOrder.class)
@DS("ds24")
public class TmpJmGoodsOrderServiceImpl
  extends ServiceImpl<TmpJmGoodsOrderMapper, TmpJmGoodsOrder>
  implements TmpJmGoodsOrderService {

  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>();
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected TmpJmGoodsOrderService self;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Resource
  protected Validator validator;

  /**
   * 创建独立站订单临时表
   * @param model 独立站订单临时表
   * @return 新数据的主键
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(TmpJmGoodsOrderVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    TmpJmGoodsOrder entity = new TmpJmGoodsOrder();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.save(entity)) {
      return entity.getId();
    }
    throw new Exception("独立站订单临时表保存失败");
  }

  /**
   * 更新独立站订单临时表
   * @param model 独立站订单临时表
   * @return 更新是否成功
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(TmpJmGoodsOrderVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    TmpJmGoodsOrder entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("独立站订单临时表不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "lastUpdateUser",
      "createTime",
      "createUser",
      "id",
      "lastUpdateTime"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      return true;
    }
    return false;
  }/**
   * 更新独立站订单临时表（带空值）
   * @param model 独立站订单临时表
   * @return 更新是否成功
   */

  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(TmpJmGoodsOrderVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    TmpJmGoodsOrder entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("独立站订单临时表不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(
        TmpJmGoodsOrder::getReasonForRejection,
        model.getReasonForRejection()
      )
      .set(TmpJmGoodsOrder::getLogisticsCompany, model.getLogisticsCompany())
      .set(TmpJmGoodsOrder::getLogisticsNo, model.getLogisticsNo())
      .set(TmpJmGoodsOrder::getMessage, model.getMessage())
      .set(TmpJmGoodsOrder::getOrderId, model.getOrderId())
      .set(TmpJmGoodsOrder::getOrderTime, model.getOrderTime())
      .set(TmpJmGoodsOrder::getPayment, model.getPayment())
      .set(TmpJmGoodsOrder::getPaymentMethod, model.getPaymentMethod())
      .set(TmpJmGoodsOrder::getPaymentTime, model.getPaymentTime())
      .set(TmpJmGoodsOrder::getPhone, model.getPhone())
      .set(TmpJmGoodsOrder::getPreferential, model.getPreferential())
      .set(TmpJmGoodsOrder::getPrice, model.getPrice())
      .set(
        TmpJmGoodsOrder::getProcessRejectReason,
        model.getProcessRejectReason()
      )
      .set(TmpJmGoodsOrder::getProtectionId, model.getProtectionId())
      .set(TmpJmGoodsOrder::getQuantity, model.getQuantity())
      .set(
        TmpJmGoodsOrder::getReasonForCancellation,
        model.getReasonForCancellation()
      )
      .set(TmpJmGoodsOrder::getLastUpdateUser, model.getLastUpdateUser())
      .set(TmpJmGoodsOrder::getReceivingTime, model.getReceivingTime())
      .set(TmpJmGoodsOrder::getRefundRemarks, model.getRefundRemarks())
      .set(TmpJmGoodsOrder::getRemarks, model.getRemarks())
      .set(TmpJmGoodsOrder::getReturnLogisticsNo, model.getReturnLogisticsNo())
      .set(TmpJmGoodsOrder::getSchemeId, model.getSchemeId())
      .set(TmpJmGoodsOrder::getShippingAddress, model.getShippingAddress())
      .set(TmpJmGoodsOrder::getShippingCity, model.getShippingCity())
      .set(TmpJmGoodsOrder::getShippingCountry, model.getShippingCountry())
      .set(TmpJmGoodsOrder::getShippingState, model.getShippingState())
      .set(TmpJmGoodsOrder::getShippingStreet, model.getShippingStreet())
      .set(TmpJmGoodsOrder::getShippingZipCode, model.getShippingZipCode())
      .set(TmpJmGoodsOrder::getSpecificationsId, model.getSpecificationsId())
      .set(TmpJmGoodsOrder::getStatus, model.getStatus())
      .set(TmpJmGoodsOrder::getSubmissionTime, model.getSubmissionTime())
      .set(TmpJmGoodsOrder::getTotal, model.getTotal())
      .set(TmpJmGoodsOrder::getActivityId, model.getActivityId())
      .set(TmpJmGoodsOrder::getAddress, model.getAddress())
      .set(TmpJmGoodsOrder::getAfterStatus, model.getAfterStatus())
      .set(TmpJmGoodsOrder::getApplyStatus, model.getApplyStatus())
      .set(TmpJmGoodsOrder::getBackendCreate, model.getBackendCreate())
      .set(TmpJmGoodsOrder::getBillAddress, model.getBillAddress())
      .set(TmpJmGoodsOrder::getCancelRemarks, model.getCancelRemarks())
      .set(TmpJmGoodsOrder::getChange, model.getChange())
      .set(TmpJmGoodsOrder::getCode, model.getCode())
      .set(TmpJmGoodsOrder::getCompletionTime, model.getCompletionTime())
      .set(TmpJmGoodsOrder::getConsignee, model.getConsignee())
      .set(TmpJmGoodsOrder::getConsumerId, model.getConsumerId())
      .set(
        TmpJmGoodsOrder::getCurrencyExchangeRateId,
        model.getCurrencyExchangeRateId()
      )
      .set(TmpJmGoodsOrder::getAccessoryRingId, model.getAccessoryRingId())
      .set(TmpJmGoodsOrder::getDeliveryTime, model.getDeliveryTime())
      .set(TmpJmGoodsOrder::getDiscountMoney, model.getDiscountMoney())
      .set(TmpJmGoodsOrder::getEarnPoints, model.getEarnPoints())
      .set(TmpJmGoodsOrder::getEmail, model.getEmail())
      .set(TmpJmGoodsOrder::getFreightPrice, model.getFreightPrice())
      .set(TmpJmGoodsOrder::getGiftCardMoney, model.getGiftCardMoney())
      .set(TmpJmGoodsOrder::getGiftId, model.getGiftId())
      .set(TmpJmGoodsOrder::getGoodsCode, model.getGoodsCode())
      .set(TmpJmGoodsOrder::getGoodsId, model.getGoodsId())
      .set(TmpJmGoodsOrder::getGoodsName, model.getGoodsName())
      .set(TmpJmGoodsOrder::getGoodsSku, model.getGoodsSku())
      .set(TmpJmGoodsOrder::getInfoText, model.getInfoText())
      .set(TmpJmGoodsOrder::getLastUpdateTime, model.getLastUpdateTime())
      .set(TmpJmGoodsOrder::getSid, model.getSid())
      .eq(TmpJmGoodsOrder::getId, model.getId())
      .update();
    if (isOk) {}
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(TmpJmGoodsOrderSearchParamPo search) {
    return false;
  }

  /**
   * 删除独立站订单临时表
   * @param id 独立站订单临时表的主键
   * @return 删除是否成功
   */
  @Override
  public boolean delete(Long id) throws Exception {
    return this.removeById(id);
  }

  /**
   * 批量删除独立站订单临时表
   * @param ids 独立站订单临时表的主键列表
   * @return 删除是否成功
   */
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<TmpJmGoodsOrderImportPo> excelToImportRow(
    TmpJmGoodsOrderImportPo row,
    Integer rowNumber,
    TmpJmGoodsOrderVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<TmpJmGoodsOrderImportPo> ir =
      new ImportRow<TmpJmGoodsOrderImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<TmpJmGoodsOrderImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new TmpJmGoodsOrderVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, TmpJmGoodsOrderImportPo.class);

    // 一般数据处理
    vo.setOrderTime(SheetUtils.tryToDateTime(row.getOrderTime()));
    vo.setPayment(SheetUtils.tryToDecimal(row.getPayment()));
    vo.setPaymentTime(SheetUtils.tryToDateTime(row.getPaymentTime()));
    vo.setPrice(SheetUtils.tryToDecimal(row.getPrice()));
    vo.setProtectionId(SheetUtils.tryToLong(row.getProtectionId()));
    vo.setQuantity(SheetUtils.tryToLong(row.getQuantity()));
    vo.setReceivingTime(SheetUtils.tryToDateTime(row.getReceivingTime()));
    vo.setSchemeId(SheetUtils.tryToLong(row.getSchemeId()));
    vo.setSpecificationsId(SheetUtils.tryToLong(row.getSpecificationsId()));
    vo.setSubmissionTime(SheetUtils.tryToDateTime(row.getSubmissionTime()));
    vo.setTotal(SheetUtils.tryToDecimal(row.getTotal()));
    vo.setBackendCreate(SheetUtils.tryToBoolean(row.getBackendCreate()));
    vo.setChange(SheetUtils.tryToDecimal(row.getChange()));
    vo.setCompletionTime(SheetUtils.tryToDateTime(row.getCompletionTime()));
    vo.setConsumerId(SheetUtils.tryToLong(row.getConsumerId()));
    vo.setCurrencyExchangeRateId(
      SheetUtils.tryToLong(row.getCurrencyExchangeRateId())
    );
    vo.setAccessoryRingId(SheetUtils.tryToLong(row.getAccessoryRingId()));
    vo.setDeliveryTime(SheetUtils.tryToDateTime(row.getDeliveryTime()));
    vo.setDiscountMoney(SheetUtils.tryToDecimal(row.getDiscountMoney()));
    vo.setEarnPoints(SheetUtils.tryToLong(row.getEarnPoints()));
    vo.setFreightPrice(SheetUtils.tryToDecimal(row.getFreightPrice()));
    vo.setGiftCardMoney(SheetUtils.tryToDecimal(row.getGiftCardMoney()));
    vo.setGiftId(SheetUtils.tryToLong(row.getGiftId()));
    vo.setGoodsId(SheetUtils.tryToLong(row.getGoodsId()));
    vo.setSid(SheetUtils.tryToLong(row.getSid()));

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<TmpJmGoodsOrderImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<TmpJmGoodsOrderImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            TmpJmGoodsOrderImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(
              TmpJmGoodsOrderImportPo row,
              AnalysisContext cxt
            ) {
              TmpJmGoodsOrderVo vo = new TmpJmGoodsOrderVo();
              ImportRow<TmpJmGoodsOrderImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<TmpJmGoodsOrderImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<TmpJmGoodsOrderImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      TmpJmGoodsOrderVo vo = new TmpJmGoodsOrderVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @Override
  public void export(
    Long templateId,
    TmpJmGoodsOrderSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addStringFields(
        "reasonForRejection",
        "logisticsCompany",
        "logisticsNo",
        "message",
        "orderId",
        "paymentMethod",
        "phone",
        "preferential",
        "processRejectReason",
        "reasonForCancellation",
        "refundRemarks",
        "remarks",
        "returnLogisticsNo",
        "shippingAddress",
        "shippingCity",
        "shippingCountry",
        "shippingState",
        "shippingStreet",
        "shippingZipCode",
        "status",
        "activityId",
        "address",
        "afterStatus",
        "applyStatus",
        "backendCreate",
        "billAddress",
        "cancelRemarks",
        "code",
        "consignee",
        "email",
        "goodsCode",
        "goodsName",
        "goodsSku",
        "infoText"
      );

      String fileName = String.format(
        "独立站订单临时表(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<TmpJmGoodsOrderExcelPo> items =
      new ArrayList<TmpJmGoodsOrderExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<TmpJmGoodsOrderItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<TmpJmGoodsOrderItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (TmpJmGoodsOrderItemVo item : list) {
        TmpJmGoodsOrderExcelPo excel = new TmpJmGoodsOrderExcelPo();
        BeanUtils.copyProperties(item, excel);
        if (item.getBackendCreate() != null) {
          excel.setBackendCreate(item.getBackendCreate() ? "是" : "否");
        }

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "独立站订单临时表(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(TmpJmGoodsOrderExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过驳回理由查询独立站订单临时表主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByReasonForRejection(String reasonForRejection) {
    return this.baseMapper.getIdByReasonForRejection(reasonForRejection);
  }

  /**
   * 通过驳回理由查询独立站订单临时表多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByReasonForRejection(List<String> list) {
    return this.baseMapper.getIdsByReasonForRejection(list);
  }

  /**
   * 通过独立站订单临时表主键查询驳回理由
   */
  @Override
  public String getReasonForRejectionById(Long id) {
    return this.baseMapper.getReasonForRejectionById(id);
  }

  /**
   * 通过独立站订单临时表主键查询驳回理由列表
   */
  @Override
  public List<String> getReasonForRejectionByIds(List<Long> ids) {
    List<Map<String, Object>> maps =
      this.baseMapper.getReasonForRejectionByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap ->
            (String) stringObjectMap.get("reasonForRejection")
          )
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 独立站订单临时表的主键
   */
  @Override
  public TmpJmGoodsOrderVo getVoById(Long id) throws Exception {
    TmpJmGoodsOrderVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }
    return vo;
  }

  /**
   * 分页查询独立站订单临时表
   * @param search 查询条件
   * @return 独立站订单临时表分页查询结果
   */
  @Override
  public Page<TmpJmGoodsOrderItemVo> pageSearch(
    TmpJmGoodsOrderSearchParamPo search
  ) {
    Page<TmpJmGoodsOrderItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(TmpJmGoodsOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 独立站订单临时表快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'TmpJmGoodsOrderOptions::' + #search.keyword"
  )
  public List<OptionItem<TmpJmGoodsOrderItemVo>> searchOptions(
    TmpJmGoodsOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询独立站订单临时表
   * @param search 查询条件
   * @return 独立站订单临时表列表查询结果
   */
  @Override
  public List<TmpJmGoodsOrderItemVo> search(
    TmpJmGoodsOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询独立站订单临时表最后更新时间
   * @param search 查询条件
   * @return 独立站订单临时表最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(TmpJmGoodsOrderSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }
}
